import request from '@/base/request';
import { ElMessage } from 'element-plus';
import { getUploadFileMD5 } from '@/utils/getFileMd5';
import { ref } from 'vue';
const CHUNK_SIZE = 10*1024 * 1024; //10MB

const progress=ref(0);
const status=ref("等待上传");
const uploadSpeed=ref(0); // 上传速度，单位：KB/s

const uploadVideo =async (file,fileMd5)=>{
    if (file.size > 1024 * 1024 * 1024) {
        ElMessage.error("文件过大");
        return false;
    }
    

    const flag=await checkFile(file,fileMd5);  //1、文件存在 2、文件不存在 3、发送错误
    if(flag===1){
        progress.value=100;
        status.value="上传成功";
        uploadSpeed.value=0;
        return true;
    }else if(flag===3){
        status.value="上传失败";
        uploadSpeed.value=0;
        return false;
    }
    status.value="正在上传"
    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);


    for (let i = 0; i < totalChunks; i++) {
        // await new Promise(resolve => setTimeout(resolve, 1000));
        const chunk = file.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
        const result=await uploadChunk(chunk,fileMd5,i);
        if(!result){
            status.value="上传失败";
            uploadSpeed.value=0;
            return false; 
        }
        progress.value=Math.round(1.0*(i+1)/totalChunks*100);
    }

    //合并分片
    status.value="正在合并";
    const response = (await (request.post(`/video/videoUploadCache/mergeChunk?fileMd5=${fileMd5}`))).data
    if(response.code!=200){
        ElMessage.error(`合并文件异常:${response.message}`);
        status.value="上传失败";
        uploadSpeed.value=0;
        return false;
    }
    status.value="上传成功";
    uploadSpeed.value=0;
    return true;

}


const checkFile = async (file,fileMd5) => {

    
    const response = (await (request.get(`/video/videoInfo/checkVideoExist?videoMd5=${fileMd5}`))).data
    if(response.code==200){
        return response.data?1:2;
    }else{
        ElMessage.error(`确认文件异常:${response.message}`);
    }

    return 3;
}




const uploadChunk = async (chunk,fileMd5,index) => {
    const chunkMd5=await getUploadFileMD5(chunk);
    //判断该分片是否已经上传
    const response = (await (request.get(`/video/videoUploadCache/checkChunkExist?chunkMd5=${chunkMd5}&fileMd5=${fileMd5}`))).data
    if(response.code==200){
        if(response.data)return true;
    }else{
        ElMessage.error(`确认文件异常:${response.message}`);
        return false;
    }

    //上传该分片
    const formData = new FormData();
    formData.append('chunk', chunk);
    formData.append('chunkMd5',chunkMd5)
    formData.append('fileMd5',fileMd5)
    
    let lastLoaded = 0;
    let lastTime = Date.now();
    
    try {
        const response2 = await request.post(`/video/videoUploadCache/uploadChunk`, formData, {
            onUploadProgress: (progressEvent) => {
                const currentTime = Date.now();
                const timeDiff = (currentTime - lastTime) / 1000; // 转换为秒
                const loaded = progressEvent.loaded - lastLoaded;
                uploadSpeed.value = loaded / timeDiff / 1024; // 转换为KB/s
                lastLoaded = progressEvent.loaded;
                lastTime = currentTime;

            }
        });
        
        if (response2.data.code !== 200) {
            ElMessage.error(`上传文件异常:${response2.data.message}，请稍后重新尝试`);
            return false;
        }
        
        return true;
    } catch (error) {
        ElMessage.error(`上传文件异常，请稍后重新尝试`);
        return false;
    }
}

export default function(){
    return {uploadVideo,progress,status,uploadSpeed};
} 